package ru.arriah.servicedesk.web.admin.action;

import java.io.IOException;
import java.util.Collection;
import java.util.regex.Pattern;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.bean.EmployeeTypeBean;
import ru.arriah.servicedesk.bean.GroupBean;
import ru.arriah.servicedesk.bean.error.EmployeeFormErrorBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;


public class ProcessEmployeeFormAction extends DumbAction {
  protected EmployeeManagerLocalHome employeeManagerHome;
  protected GroupManagerLocalHome groupManagerHome;
  protected EmployeeFormErrorBean formErrorBean; 
  
  public ProcessEmployeeFormAction() throws NamingException {
    super();
    
    employeeManagerHome =
      Utils.getEmployeeManagerHomeInterface();
   
    groupManagerHome =
     Utils.getGroupManagerHomeInterface();   
  }
  
  
  public boolean isValid(
    EmployeeBean employeeBean,
    EmployeeManagerLocalObject employeeManager
  ) {
    boolean valid = true;
    formErrorBean = new EmployeeFormErrorBean();           
    
    Pattern email = 
      Pattern.compile(
        config.getProperty("REGEXP.EMAIL"),
        Pattern.CASE_INSENSITIVE
      );
    
    if (employeeBean.getFirstName().equals("")) {
      formErrorBean.setFirstName(
        config.getProperty("ERROR.EMPLOYEEFORM.FIRSTNAME")
      );
      valid = false;
    }
    
    if (employeeBean.getLastName().equals("")) {
      formErrorBean.setLastName(
        config.getProperty("ERROR.EMPLOYEEFORM.LASTNAME")
      );
      valid = false;
    }
    
    if (employeeBean.getMiddleName().equals("")) {
      formErrorBean.setMiddleName(
        config.getProperty("ERROR.EMPLOYEEFORM.MIDDLENAME")
      );
      valid = false;
    }
    
    if (employeeBean.getGroupId() == 0) {
      formErrorBean.setGroup(
        config.getProperty("ERROR.EMPLOYEEFORM.GROUP")
      );
      valid = false;
    }
    
    if (employeeBean.getTypeId() == 0) {
      formErrorBean.setType(
        config.getProperty("ERROR.EMPLOYEEFORM.TYPE")
      );
      valid = false;
    }
    
    if (employeeBean.getPassword().equals("") || employeeBean.getPassword() == null) {
      formErrorBean.setPassword(
        config.getProperty("ERROR.EMPLOYEEFORM.PASSWORD")
      );
      valid = false;
    }
    
    if (employeeBean.getRePassword().equals("") || employeeBean.getRePassword() == null) {
      formErrorBean.setRePassword(
        config.getProperty("ERROR.EMPLOYEEFORM.REPASSWORD")
      );
      valid = false;
    } else if (!employeeBean.getRePassword().equals(employeeBean.getPassword())) {
      formErrorBean.setRePassword(
        config.getProperty("ERROR.EMPLOYEEFORM.REPASSWORD_INVALID")
      );
      valid = false;
    }
    
    if (employeeBean.getLogin().equals("") || employeeBean.getLogin() == null) {
      formErrorBean.setLogin(
        config.getProperty("ERROR.EMPLOYEEFORM.LOGIN")
      );
      valid = false;
    } else {      
      if (!employeeManager.isLoginUnique(employeeBean.getLogin(), employeeBean.getTypeId(), employeeBean.getId())) {
        formErrorBean.setLogin(
            config.getProperty("ERROR.EMPLOYEEFORM.LOGIN_EXIST")
        );
          valid = false;
        }
      }    
                          
    if (employeeBean.getEmail() == null || employeeBean.getEmail().equals("")) {
      formErrorBean.setEmail(
        config.getProperty("ERROR.EMPLOYEEFORM.EMAIL_INVALID")
      );
      valid = false;
    } else if (!email.matcher(employeeBean.getEmail()).matches()) {
      formErrorBean.setEmail(
        config.getProperty("ERROR.EMPLOYEEFORM.EMAIL_INVALID")
      );
      valid = false;
    }             
        
    return valid;    
  }

  
  public String execute(ActionMapping actionMapping,
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    try {
      EmployeeBean employeeBean = new EmployeeBean();                             
   
      employeeBean.setId(idVal(request.getParameter("id")));
      employeeBean.setFirstName(request.getParameter("firstName"));
      employeeBean.setLastName(request.getParameter("lastName"));
      employeeBean.setMiddleName(request.getParameter("middleName"));
      employeeBean.setEmail(request.getParameter("email"));
      employeeBean.setGroupId(idVal(request.getParameter("group_id")));
      employeeBean.setLogin(request.getParameter("login"));
      employeeBean.setPassword(request.getParameter("password"));
      employeeBean.setRePassword(request.getParameter("repassword"));
      employeeBean.setTypeId(idVal(request.getParameter("type_id")));      
      
      EmployeeManagerLocalObject employeeManager = 
        employeeManagerHome.create();                  
      
      if (!isValid(employeeBean, employeeManager)) {
         
        addErrorMessage(
            request,
            config.getProperty("ERROR.EMPLOYEEFORM_FIELDS_INVALID")
        );
        
        GroupManagerLocalObject groupManager =
          groupManagerHome.create();
        
        Collection<GroupBean> groupsList = 
          groupManager.selectGroups();
                  
        Collection<EmployeeTypeBean> typesList = 
          employeeManager.selectEmployeeTypes();
        
        employeeManager.remove();
        groupManager.remove();                
        
        request.setAttribute("typesList", typesList);
        request.setAttribute("groupsList", groupsList);
        request.setAttribute("employeeBean", employeeBean);        
        request.setAttribute("error", formErrorBean);

        return actionMapping.getFailureTarget();
      }
                       
      if(employeeBean.getId() == 0) {
        employeeManager.addEmployee(employeeBean);
        
        addInfMessage(
           request,
           config.getProperty("INF.EMPLOYEE_ADDED")
        );
        
      } else {        
        employeeManager.updateEmployee(employeeBean);        
        
        addInfMessage(
           request,
           config.getProperty("INF.EMPLOYEE_UPDATED")          
        );
        
      }            
       
// Prepare employees list
      
      Collection<EmployeeBean> employessList = 
        employeeManager.selectAll();                  
      
      employeeManager.remove();
      
      request.setAttribute("employessList", employessList);
      
      return actionMapping.getSuccessTarget();
    } catch (Exception e) {
      handleException(e, "execute");
      throw new InternalException("ErrorMessage.internal");
    }
  }
}